<?
class smtp extends Think {
	
	static function connect() {
		
		$o = fsockopen ( C ( 'SMTP_HOST' ), C ( 'SMTP_PORT' ) );
		
		$GLOBALS['log'] .= fgets ( $o, 1024 ) . br;
		
		if ($o) {
			
			$smtp = array(
				
				array(
					'HELLO',
					'HELO OurYou',
					'220,250',
				),
				array(
					'用户登录',
					'AUTH LOGIN',
					'334',
				),
				array(
					'用户名',
					base64_encode( C ( 'SMTP_USER' ) ),
					'334',
				),
				array(
					'密码',
					base64_encode( C ( 'SMTP_PASS' ) ),
					'235',
				),
			);
			
			smtp::run ( $o, $smtp );
			
			return $o;
			
		}else{
			
			return 0;
		}
	}
	static function send( $arr ) {
		
		$o			= $arr['obj'];
		$to			= $arr['to'] == null ? C ( 'SMTP_TO' ) : $arr['to'];
		$subject	= iconv ( 'UTF-8', 'GBK', $arr['subject'] );
		$content	= iconv ( 'UTF-8', 'GBK', $arr['content'] );
		
		$smtp = array(
			
			array(
				'MAIL FROM',
				'MAIL FROM: '. smtp::getAddress ( C ( 'SMTP_FROM' ) ),
				'250',
			),
			array(
				'RCPT TO',
				'RCPT TO: ' . $to,
				'250',
			),
			array(
				'DATA',
				'DATA',
				'354',
			),
			array(
				'To',
				'To: ' . $to,
			),
			array(
				'Reply-To',
				'Reply-To: ' . C ( 'SMTP_RE' ),
			),
			array(
				'From',
				'From: ' . C ( 'SMTP_FROM' ),
			),
			array(
				'Subject',
				'Subject: '. $subject,
			),
			array(
				'Content-type',
				'Content-type: text/html; charset=gbk',
			),
			array(
				'Content-Transfer-Encoding',
				'Content-Transfer-Encoding: base64',
			),
			array(
				'吉行Header结束',
				"\r\n",
			),
			array(
				'主体',
				base64_encode( $content ),
			),
			array(
				'结束邮件',
				".",
				'250',
			),

		);
		
		smtp::run ( $o, $smtp );
		
		return 1;

	}
	static function close($o) {
		
		$smtp = array(
			array(
				'QUIT',
				"QUIT",
				'250',
			),
		);
		
		smtp::run ( $o, $smtp );
		
		fclose ( $o );
		
//		echo $GLOBALS['log'];
	}
	static function run($o, $smtp) {

		foreach ( $smtp as $v ) {
			
			if (!is_array ( $v )) {
				continue;
			}
			
			fputs ( $o, $v [1] . "\r\n" );

			if ($v [2]) {
				
				$fg = fgets ( $o, 1024 );
				$GLOBALS['log'] .= $fg . br;
			}
			if ($v [1] == '.'){
				
				return $fg=='250';
			}

		}
	}
	static function getAddress($email) {
		
		$a = strpos ( $email, '<' );
		$b = strpos ( $email, '>' );
		
		if ($a !== false && $b !== false) {
			return substr ( $email, $a + 1, $b - strlen ( $email ) );
		} else {
			return $email;
		}
	}
}
?>